package com.rockgle.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

import com.rockgle.reader.ContentLoader;
import com.rockgle.reader.PreferenceMonitor;

public class RockgleService extends Service implements Runnable{
	private static boolean running = false;
	private Handler handler= new Handler();
	private int frequency = 300000;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		String freq = PreferenceMonitor.getRefreshRateService();
		if (!freq.equals("null")){
			try{
				this.frequency = Integer.parseInt(freq);
			}catch(NumberFormatException numEx){
				this.frequency = 300000;
			}
		}
		//Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		RockgleService.running = false;
		//Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
		handler.removeCallbacks(this);
		System.runFinalizersOnExit(true);
	}

	@Override
	public void onStart(Intent intent, int startId) {

		super.onStart(intent, startId);
		RockgleService.running = true;
		run();
	}
	
	public static boolean isRunning(){
		return RockgleService.running;
	}
	
	@Override
	public void run() {
		if(PreferenceMonitor.getUseService()){
			new ContentLoader(null).execute();
			handler.postDelayed(this, frequency);
		}else{
			this.stopSelf();
		}
	}
}
